package main

import (
	"fmt"
	"log"
	"net/http"
	"os"
	"os/signal"
	"syscall"

	"github.com/nacos-group/nacos-sdk-go/v2/clients"
	"github.com/nacos-group/nacos-sdk-go/v2/clients/naming_client"
	"github.com/nacos-group/nacos-sdk-go/v2/common/constant"
	"github.com/nacos-group/nacos-sdk-go/v2/vo"
)

func main() {
        var SvrName string = "sqlsvr"
        var SvrPort int = 21801
	var SvrIp string = "192.168.31.135"
        var NacosSvrIp string = "192.168.31.134"
        var NacosSvrPort uint64 = 8848

	// Nacos 配置
	serverConfigs := []constant.ServerConfig{
		{
			IpAddr: NacosSvrIp, // Nacos 服务器地址
			Port:   NacosSvrPort,             // Nacos 服务器端口
		},
	}

	clientConfig := constant.ClientConfig{
		NamespaceId:         "default", // 如果使用了命名空间，请填写对应ID
		TimeoutMs:           5000,
		NotLoadCacheAtStart: true,
		LogDir:              "./nacos/log",
		CacheDir:            "./nacos/cache",
		LogLevel:            "debug",
	}

	// 创建 Nacos Naming 客户端
	namingClient, err := clients.NewNamingClient(vo.NacosClientParam{
		ClientConfig:  &clientConfig,
		ServerConfigs: serverConfigs,
	})
	if err != nil {
		log.Fatalf("创建 Nacos Naming 客户端失败: %v\n", err)
	}

	// 服务信息
	serviceName := SvrName
	ip := SvrIp // 服务实例 IP
	port := SvrPort           // 服务实例端口

	// 注册服务到 Nacos
	registerService(namingClient, serviceName, ip, uint64(port))

	// 捕获系统信号，用于优雅退出和注销服务
	handleGracefulShutdown(namingClient, serviceName, ip, uint64(port))

	// 启动 HTTP 服务
	startHTTPServer(uint64(port))
}

// registerService 注册服务到 Nacos
func registerService(namingClient naming_client.INamingClient, serviceName, ip string, port uint64) {
	_, err := namingClient.RegisterInstance(vo.RegisterInstanceParam{
		ServiceName: serviceName,
		Ip:          ip,
		Port:        port,
		Weight:      1.0,
		Enable:      true,
		Healthy:     true,
		Ephemeral:   true, // 临时实例
	})
	if err != nil {
		log.Fatalf("服务注册失败: %v\n", err)
	}
	fmt.Printf("服务注册成功: %s (%s:%d)\n", serviceName, ip, port)
}

// handleGracefulShutdown 处理优雅关闭
func handleGracefulShutdown(namingClient naming_client.INamingClient, serviceName, ip string, port uint64) {
	go func() {
		c := make(chan os.Signal, 1)
		signal.Notify(c, os.Interrupt, syscall.SIGTERM)

		<-c // 等待信号

		// 注销服务
		_, err := namingClient.DeregisterInstance(vo.DeregisterInstanceParam{
			ServiceName: serviceName,
			Ip:          ip,
			Port:        port,
		})
		if err != nil {
			log.Printf("服务注销失败: %v\n", err)
		} else {
			fmt.Printf("服务已成功注销: %s (%s:%d)\n", serviceName, ip, port)
		}

		os.Exit(0)
	}()
}

// startHTTPServer 启动 HTTP 服务
func startHTTPServer(port uint64) {
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintln(w, "Hello, Nacos!")
	})

	addr := fmt.Sprintf(":%d", port)
	fmt.Printf("HTTP 服务启动中，监听地址: %s\n", addr)
	if err := http.ListenAndServe(addr, nil); err != nil {
		log.Fatalf("HTTP 服务启动失败: %v\n", err)
	}
}

